﻿using Domain.IRepositorys;
using Infrastructure.UniOfWorkBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Application.App
{
    public class MessageApplication
    {
        public IMessageRepository messageRepository { get; set; }
        public IMessageUserRepository messageUserRepository { get; set; }
        public IEFUnitOfWork efUnitOfWork { get; set; }
        public object GetMessages(int userID)
        {
            var messages = messageRepository.Entities.Where(i => i.Status == 0 && !i.IsDelete).OrderByDescending(i => i.CT).Take(50).ToArray();

            var u = messageUserRepository.Entities.FirstOrDefault(i => i.UserID == userID);

            int sr = 0, ar = 0;
            if (u != null)
            {
                if (u.LastReadSystem != null)
                {
                    sr = messages.Count(i => i.From == 0 && i.CT > u.LastReadSystem);
                }
                else
                {
                    sr = messages.Count(i => i.From == 0);
                }
                if (u.LastReadManager != null)
                {
                    ar = messages.Count(i => i.From == 1 && i.CT > u.LastReadManager);
                }
                else
                {
                    ar = messages.Count(i => i.From == 1);
                }
            }
            else
            {
                sr = messages.Count(i => i.From == 0);
                ar = messages.Count(i => i.From == 1);
            }

            return new { SystemMsgs = messages.Where(i => i.From == 0), ManagerMsgs = messages.Where(i => i.From == 1), SystemUnRead = sr, ManagerUnRead = ar };
        }

        public bool SetMessageRead(int userID, int from)
        {
            var u = messageUserRepository.Entities.FirstOrDefault(i => i.UserID == userID);
            if (u == null)
            {
                u = new MessageUserAggregate();
                u.UserID = userID;
                u = messageUserRepository.Insert(u);
            }
            if (from == 0) u.LastReadSystem = DateTime.Now;
            else u.LastReadManager = DateTime.Now;

            efUnitOfWork.Commit();
            return true;
        }
    }
}
